package com.nj.liandi.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.nj.liandi.common.utils.R;
import com.nj.liandi.gulimall.ware.feign.MemberFeignService;
import com.nj.liandi.gulimall.ware.vo.FareVo;
import com.nj.liandi.gulimall.ware.vo.MemberAddressVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.liandi.common.utils.PageUtils;
import com.nj.liandi.common.utils.Query;

import com.nj.liandi.gulimall.ware.dao.WareInfoDao;
import com.nj.liandi.gulimall.ware.entity.WareInfoEntity;
import com.nj.liandi.gulimall.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("name", key)
                        .or().like("address", key)
                        .or().eq("areacode", key);
            });
        }
        IPage<WareInfoEntity> page = this.page(new Query<WareInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R r = memberFeignService.addInfo(addrId);
        if (r.getCode()==0) {
            MemberAddressVo addressVo = r.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
            });
            if (addressVo!=null) {
                String phone = addressVo.getPhone();
                String substring = phone.substring(phone.length() - 1, phone.length());
                fareVo.setFare(new BigDecimal(substring));
                fareVo.setAddress(addressVo);
                return fareVo;
            }
        }
        return null;
    }

}